package com.zz.client.factory;

import com.zz.client.handle.ClientChannelHandler;
import com.zz.client.handle.LocalHandler;
import com.zz.common.coder.ByteArrayCodec;
import com.zz.common.coder.GzipCodec;
import com.zz.common.handle.*;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.stream.ChunkedWriteHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * bootstrap 工厂
 *
 * @author zz
 */
@Slf4j
public class ClientBootstrapFactory {


    /**
     * 客户端 bootstrap
     * @param localBootstrap
     * @param workerGroup
     * @return
     */
    public static Bootstrap createClientBootstrap(Bootstrap localBootstrap, NioEventLoopGroup workerGroup) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {

            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                // 压缩解压
                ch.pipeline().addLast(new GzipCodec());
                ch.pipeline().addLast(new TunnelProtocolDecode(Integer.MAX_VALUE, 0, 4, 0, 0));
                ch.pipeline().addLast(new TunnelProtocolEncode());
                // 请求分片处理
                ch.pipeline().addLast(new ChunkedWriteHandler());
                //ch.pipeline().addLast(new IdleCheckHandler(IdleCheckHandler.READ_IDLE_TIME, IdleCheckHandler.WRITE_IDLE_TIME - 10, 0));
                ch.pipeline().addLast(new ClientChannelHandler(bootstrap, localBootstrap));
            }
        });
        return bootstrap;
    }

    /**
     * 本地 bootstrap
     * @param localGroup
     * @return
     */
    public static Bootstrap createLocalBootstrap(NioEventLoopGroup localGroup) {
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(localGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel channel) throws Exception {
                channel.pipeline().addLast(new ByteArrayCodec());
                channel.pipeline().addLast(new ChunkedWriteHandler());
                channel.pipeline().addLast(new LocalHandler());
            }
        });
        return bootstrap;
    }
}
